package com.stone.design.practice;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.stone.design.practice.broadcastreceiver.BroadcastReceiverActivity;
import com.stone.design.practice.eventbus.Event;
import com.stone.design.practice.eventbus.EventBusActivity;
import com.stone.design.practice.mvp.view.SecondActivity;
import com.stone.design.practice.util.FileUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.os.Environment.DIRECTORY_DOWNLOADS;

public class MainActivity extends AppCompatActivity {


    public static final String TAG = "Stone";
    public static final int FLAG_SUCCESS = 1; // 创建成功
    public static final int FLAG_EXISTS = 2; // 已存在
    public static final int FLAG_FAILED = 3; // 创建失败
    @BindView(R.id.tv_show_text)
    TextView mTvShowText;

    private static class MyHandler extends Handler {
        private WeakReference<Activity> reference;

        public MyHandler(Activity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (reference.get() != null) {
                switch (msg.what) {

                    case 0: {

                        Log.e("Stone", "handleMessage(MainActivity.java:40)-->>" + "ddd");
                        break;
                    }
                    case 65: {

                        Log.e("Stone", "handleMessage(MainActivity.java:45)-->>" + "65");
                        break;
                    }
                    default:
                        break;

                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);

        MyHandler myHandler = new MyHandler(this);
        myHandler.sendEmptyMessage(0);


        //region 注释
        // Button button = findViewById(R.id.button);
        /*PieView f = findViewById(R.id.pie_view);
        PieData pieData = new PieData("1", 20);
        PieData pieData1 = new PieData("1", 20);
        PieData pieData2 = new PieData("1", 20);

        List<PieData> list = new ArrayList<>();
        list.add(pieData);
        list.add(pieData1);
        list.add(pieData2);
        f.setData(list);*/
        /*LinearLayout ll = findViewById(R.id.ll_my);
        MyView myView = findViewById(R.id.my);

        ll.setOnClickListener(this);
        myView.setOnClickListener(this);*/

        //endregion


        //region 注册eventBus

        EventBus.getDefault().register(this);

        //endregion

    }



    public int createDir (String dirPath) {

        File dir = new File(dirPath);
        //文件夹是否已经存在
        if (dir.exists()) {
            Log.w(TAG,"The directory [ " + dirPath + " ] has already exists");
            return FLAG_EXISTS;
        }
        if (!dirPath.endsWith(File.separator)) {//不是以 路径分隔符 "/" 结束，则添加路径分隔符 "/"
            dirPath = dirPath + File.separator;
        }
        //创建文件夹
        if (dir.mkdirs()) {
            Log.d(TAG,"create directory [ "+ dirPath + " ] success");
            return FLAG_SUCCESS;
        }

        Log.e(TAG,"create directory [ "+ dirPath + " ] failed");
        return FLAG_FAILED;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        String  st = event.getMessage();
        mTvShowText.setText(st);
    }

    @OnClick({R.id.iv_my, R.id.btn_event, R.id.btn_go})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_my: {

                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
                break;
            }

            case R.id.btn_event: {
                Intent intent = new Intent(MainActivity.this, EventBusActivity.class);
                startActivity(intent);
                break;
            }

            case R.id.btn_go: {
/*
                Intent intent = new Intent(MainActivity.this, BroadcastReceiverActivity.class);
                startActivity(intent);*/
                /*System.out.println("");


                String sd = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS).getAbsolutePath() +
                        "/" +getPackageName() + "/" + "stone";

                int code = createDir(sd);*/

                String path = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS).getAbsolutePath() +
                        "/" + getPackageName() + "/" + "stone.txt";
                int result = FileUtils.CreateFile(path);
                //showResult(result);

                Base base = new Base("哈哈");
                boolean ok = saveObject(base, path);

                Base base1 = (Base) readObject(path);


                //endregion

                break;
            }



            default:
                break;

        }
    }


    /**
     * 显示结果
     * @param result 结果码
     */
    private void showResult (int result) {
        switch (result) {
            case FileUtils.FLAG_SUCCESS:
                mTvShowText.setText("result: create success");
                break;
            case FileUtils.FLAG_EXISTS:
                mTvShowText.setText("result: already exist");
                break;
            case FileUtils.FLAG_FAILED:
                mTvShowText.setText("result: create failed");
                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }


    /**
     * 序列化对象
     * @param object
     * @param path
     * @return
     */
    private boolean saveObject(Object object, String path) {
        if (object == null) {
            return false;
        }

        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(path));
            oos.writeObject(object);
            oos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 反序列化对象
     * @param path
     * @return
     */
    private Object readObject(String path) {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(path));
            try {
                return ois.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

}
